<?php
/**
 * Created by PhpStorm.
 * User: Rei
 * Date: 16/5/4
 * Time: 13:38
 * Mail: rei@king.moe
 */

namespace Home\Controller;

use Think\Controller;

class UserController extends Controller
{

    //载入登陆视图
    public function login()
    {
        if(session("?uid")){
            $this->redirect("/");
        }else{
            $this->display('index/index');
        }
    }

    //用户登陆
    public function signIn()
    {
        $data = array();
        $result = array(
            'code' => 0,
            'message' => '未知错误'
        );

        $data['password'] = I('post.password', '', 'md5');
        $data['email'] = check_str(I('post.email'));

        if (D('User')->signIn($data)) {
            $result['code'] = 1;
            $result['message'] = '登陆成功';
        } else {
            $result['code'] = 2;
            $result['message'] = '不存在的邮箱或密码';
        }

        $this->ajaxReturn($result, 'json');
    }

    //用户注册
    public function signUp()
    {
        $data = array();
        $result = array(
            'code' => 0,
            'message' => '未知错误'
        );
        $time = time();

        $data['username'] = check_str(I('post.username'));
        $data['password'] = I('post.password', '', 'md5');
        $data['email'] = check_str(I('post.email'));
        $data['regtoken'] = md5($data['username'] . $data['email'] . $time);
        $data['exptime'] = 0; //邮箱激活标识
        $data['avatar'] = "/Public/images/avatar.png"; //初始头像

        //邮箱验证
        if (D('User')->checkMail($data['email'])) {
            //添加数据库
            $uid = D('User')->addUser($data);
            if ($uid) {
                //发送验证邮件
                $send_mail = $this->sendVerifyMail($data['email'], $uid, $data['username'], $data['regtoken']);
                //生成登陆Token
                D('User')->createUserToken($uid);
                $result['code'] = 1;
                $result['message'] = $send_mail;
            } else {
                $result['code'] = 2;
                $result['message'] = '注册失败';
            }
        } else {
            $result['code'] = 2;
            $result['message'] = '注册失败';
        }

        $this->ajaxReturn($result, 'json');
    }

    //未注册邮箱检测
    public function testMail()
    {
        $email = check_str(I('post.email', ''));
        if ($email && D('User')->checkMail($email)) {
            $this->ajaxReturn(array('success' => '邮箱可用'), 'json');
        } else {
            $this->ajaxReturn(array('error' => '邮箱已注册'), 'json');
        }
    }

    //验证邮件发送
    public function sendVerifyMail($to, $uid, $user, $token)
    {
        $email = base64_encode($to);
        $verifyUrl = "http://pin.king.moe/home/user/verify?uid=$uid&email=$email&token=$token";
        $title = 'PinPaper用户激活邮件';
        $time = date("Y/m/d H:i:s");
        $content = "您好，$user ：<br/><p>欢迎加入PinPaper！请点击下面的链接来认证您的邮箱。</p><a href='" . $verifyUrl . "' target='_blank'>$verifyUrl</a>如果您的邮箱不支持链接点击，请将以上链接地址拷贝到你的浏览器地址栏中认证。<p>发件时间：$time</p><p>此邮件为系统自动发出的，请勿直接回复。</p>";
        return sendMail($to, $title, $content);
    }

    //邮箱验证
    public function verify()
    {
        $get_token = check_str(I('get.token', ''));
        $get_email = check_str(I('get.email', '', 'base64_decode'));
        $get_uid = check_str(I('get.uid', ''));
        $result = D('User')->verifyMailToken($get_uid, $get_email, $get_token);
        if ($result) {
            $this->success('邮箱验证成功', '/', 3);
        } else {
            $this->error('邮箱验证失败', '/', 3);
        }
        exit;
    }


    /**
     *
     * 同步评论数据
     *
     */
    function comments()
    {
        if (isset($_POST['action'])) {
            $log_file = fopen('./Public/log/duoshuo.log','a');
            fwrite($log_file, date('Y/m/d H:i:s')."\nLog Start:\n");
            $limit = 1;

            $last_log_id = D('Log')->getField('since_id');

            //初始化
            $ch = curl_init();

            //设置选项，包括URL
            curl_setopt($ch, CURLOPT_URL, "http://api.duoshuo.com/log/list.json?short_name=8akarei&secret=06711d77480e319eebf8013ff42885d2&since_id=$last_log_id");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);

            //执行并获取HTML文档内容
            $output = curl_exec($ch);

            //释放curl句柄
            curl_close($ch);

            $output = json_decode($output, true);

            if (!isset($output['response'])) {
                //处理错误,错误消息$response['message'], $response['code']
                echo $output['message'] . $output['code'];
            } else {
                //遍历返回的response，你可以根据action决定对这条评论的处理方式。
                foreach ($output['response'] as $log) {
                    $nid = $log['meta']['thread_key'];
                    switch ($log['action']) {
                        case 'create':
                            $status = D('News')->addComments($log['meta']);
                            fwrite($log_file, " Operation:Create ID:$nid Status:$status\n");
                            break;
                        case 'delete':
                            //这条评论是删除的评论
                            $status = D('News')->deleteComments($log['meta']);
                            fwrite($log_file, " Operation:Delete Status:$status\n");
                            break;
                        case 'delete-forever':
                            //彻底删除的评论
                            $status = D('News')->deleteComments($log['meta']);
                            fwrite($log_file, " Operation:Delete Status:$status\n");
                            break;
                        default:
                            break;
                    }
                    if (strlen($log['log_id']) > strlen($last_log_id) || strcmp($log['log_id'], $last_log_id) > 0) {
                        $last_log_id = $log['log_id'];
                    }
                }
                D('Log')->where('1')->setField(array('since_id'=>$last_log_id));
            }
            fclose($log_file);
        }
    }
}